import { ref, unref, watch } from 'vue'

import type { BwDomNodeInfo } from '../model'
export function useDomNode(props, emit) {
  const isExpand = ref<boolean>(false)
  const isExpandIcon = ref<boolean>(true)

  /** 展开节点信息 */
  const onExpand = () => {
    const nodeInfo: BwDomNodeInfo = props.data

    isExpand.value = !isExpand.value
    nodeInfo.isExpand = !nodeInfo.isExpand
  }

  /** 临时隐藏节点 */
  const onHide = (nodeId: string, isHide: boolean) => {
    emit('hide', nodeId, isHide)
  }

  /** 选中节点 */
  const onSelect = (nodeId: string) => {
    emit('select', nodeId)
  }

  /** 删除节点 */
  const onDelete = (nodeId: string) => {
    emit('delete', nodeId)
  }

  watch(
    () => props.data,
    (newVal?: BwDomNodeInfo) => {
      const { children } = newVal ?? {}

      isExpand.value = !!newVal?.isExpand
      isExpandIcon.value = !!(Array.isArray(children) && children.length)
    },
    { deep: true, immediate: true }
  )

  return {
    isExpand,
    isExpandIcon,

    onHide,
    onExpand,
    onSelect,
    onDelete,
  }
}
